import 'dart:convert';

import 'package:bitcoin_mine/api/api.dart';
import 'package:bitcoin_mine/common/BaseEntity.dart';
import 'package:bitcoin_mine/common/global.dart';
import 'package:bitcoin_mine/model/pay_order_success.dart';
import 'package:bitcoin_mine/services/ExamplePaymentQueueDelegate.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

import '../http/http_request.dart';

class InAppPurchaseService extends GetxService {
  static final InAppPurchaseService _instance =
      InAppPurchaseService._internal();
  factory InAppPurchaseService() => _instance;
  InAppPurchaseService._internal();

  final RxString errorMessage = ''.obs;
  final RxBool isLoadingProducts = false.obs;
  final RxList<ProductDetails> availableProducts = <ProductDetails>[].obs;
  final RxList<String> productIds = <String>[].obs;
  String? currentPayOrder;
  RxBool isPurchasing = false.obs;

  late InAppPurchaseStoreKitPlatformAddition iosPlatformAddition;

  @override
  void onInit() {
    super.onInit();
    _initializeInAppPurchase();
  }

  /// 初始化内购
  Future<void> _initializeInAppPurchase() async {
    try {
      // 检查是否支持内购
      final bool isAvailable = await InAppPurchase.instance.isAvailable();
      if (!isAvailable) {
        print('内购功能不可用');
        return;
      }
      final transactions = await SKPaymentQueueWrapper().transactions();
      transactions.forEach((transaction) async {
        await SKPaymentQueueWrapper().finishTransaction(transaction);
      });

      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          InAppPurchase.instance
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();

      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());

      // 启动购买状态监听
      _listenToPurchaseUpdates();
    } catch (e) {
      errorMessage.value = '初始化内购失败: $e';
      print('初始化内购失败: $e');
    }
  }

  /// 加载内购产品
  Future<void> loadProducts() async {
    try {
      isLoadingProducts.value = true;
      errorMessage.value = '';

      productIds.addAll(Global.goods.map((e) => e.product_id).toList() ?? []);

      // 获取产品详情
      final ProductDetailsResponse response = await InAppPurchase.instance
          .queryProductDetails(productIds.toSet());

      if (response.notFoundIDs.isNotEmpty) {
        print('未找到的产品ID: ${response.notFoundIDs}');
      }

      if (response.error != null) {
        errorMessage.value = '加载产品失败: ${response.error}';
        print('加载产品失败: ${response.error}');
        return;
      }

      // 更新可用产品列表
      availableProducts.value = response.productDetails;

      print('成功加载 ${response.productDetails.length} 个产品');
      for (final product in response.productDetails) {
        // 调试：打印产品类型和实际类型信息
        // print('产品 ${product.id} 的类型: ${product.runtimeType}');
        // print(
        //   '是否为 AppStoreProductDetails: ${product is AppStoreProductDetails}',
        // );
        // print(
        //   '是否为 AppStoreProduct2Details: ${product is AppStoreProduct2Details}',
        // );

        // 尝试通过反射或类型转换获取折扣信息
        // 方法1: 直接类型检查 StoreKit 2
        AppStoreProduct2Details? appStoreProduct;
        try {
          appStoreProduct = product as AppStoreProduct2Details;
        } catch (e) {
          // 类型转换失败，尝试其他方式
          print('无法转换为 AppStoreProductDetails: $e');
        }
        // print('原价: ${product.price}');
        if (appStoreProduct != null) {
          final sk2Product = appStoreProduct.sk2Product;
          final discounts = sk2Product.subscription?.promotionalOffers;
          // print("所有内容：${jsonEncode(sk2Product)}");
          if (discounts != null && discounts.isNotEmpty) {
            print('产品 ${appStoreProduct.id} 有 ${discounts.length} 个折扣');
            final discount = discounts.first;
            print(
              '折扣 价格=${discount.period}, '
              '折扣方式 ${discount.paymentMode.name}, '
              '折扣价格 ${discount.price} ',
              // '周期单位=${discount..unit}, '
              // '周期长度=${discount.periodCount}',
            );
            final good = Global.goods.firstWhere(
              (element) => element.product_id == product.id,
            );
            good.original_price = product.price;
            good.discount_price = discount.price.toString();
          } else {
            // print('产品 ${appStoreProduct.id} 没有折扣');
          }
        }
        // 尝试 StoreKit 2 (AppStoreProduct2Details)
        // else {
        //   try {
        //     final appStoreProduct2 = product as AppStoreProduct2Details;
        //     final sk2Product = appStoreProduct2.sk2Product;
        //     print('产品 ${appStoreProduct2.id} 是 StoreKit2 产品');
        //     print('SK2 产品信息: ${sk2Product.id}, ${sk2Product.displayPrice}');
        //   } catch (e) {
        //     print('产品 ${product.id} 既不是 StoreKit1 也不是 StoreKit2 类型: $e');
        //   }
        // }

        // print(
        //   '产品: ${product.id}, 价格: ${product.price}, rawPrice: ${product.rawPrice}, 标题: ${product.title}, 描述: ${product.description}, 货币符号: ${product.currencySymbol}, 货币代码: ${product.currencyCode}',
        // );
      }
    } catch (e) {
      errorMessage.value = '加载产品异常: $e';
      print('加载产品异常: $e');
    } finally {
      isLoadingProducts.value = false;
    }
  }

  /// 根据层级和计划获取对应的产品ID
  String _getProductId(int tier, int plan) {
    final tierNames = ['basic', 'moderate', 'advanced', 'top'];
    final planNames = ['month', 'season', 'year'];

    if (tier >= tierNames.length || plan >= planNames.length) {
      return '';
    }

    return '${tierNames[tier]}_${planNames[plan]}';
  }

  /// 获取当前选择的产品
  ProductDetails? getCurrentProduct(int tier, int plan) {
    final productId = _getProductId(tier, plan);
    if (productId.isEmpty) return null;

    try {
      return availableProducts.firstWhere((product) => product.id == productId);
    } catch (e) {
      return null;
    }
  }

  /// 获取当前选择的产品
  ProductDetails? getProductInfo(String productId) {
    if (productId.isEmpty) return null;

    try {
      return availableProducts.firstWhere((product) => product.id == productId);
    } catch (e) {
      return null;
    }
  }

  /// 获取产品的折扣价格信息
  /// 返回第一个折扣的价格（字符串格式），如果没有折扣则返回 null
  String? getProductDiscountPrice(String productId) {
    try {
      final product = getProductInfo(productId);
      if (product == null) return null;

      // StoreKit 1
      if (product is AppStoreProductDetails) {
        final discounts = product.skProduct.discounts;
        if (discounts.isNotEmpty) {
          // 返回第一个折扣的价格，格式化为字符串
          final price = discounts.first.price;
          return price.toString();
        }
      }
      // StoreKit 2 - 需要检查是否有折扣相关的方法
      else if (product is AppStoreProduct2Details) {
        // StoreKit 2 的折扣信息可能需要不同的访问方式
        print('StoreKit 2 产品暂不支持折扣价格获取');
      }

      return null;
    } catch (e) {
      print('获取折扣价格失败: $e');
      return null;
    }
  }

  /// 获取产品的所有折扣信息
  List<Map<String, dynamic>>? getProductDiscounts(String productId) {
    try {
      final product = getProductInfo(productId);
      if (product == null) return null;

      // StoreKit 1
      if (product is AppStoreProductDetails) {
        final discounts = product.skProduct.discounts;
        if (discounts.isNotEmpty) {
          return discounts.map((discount) {
            return {
              'price': discount.price.toString(),
              'numberOfPeriods': discount.numberOfPeriods,
              'subscriptionPeriod': {
                'unit': discount.subscriptionPeriod.unit.toString(),
                'numberOfUnits': discount.subscriptionPeriod.numberOfUnits,
              },
            };
          }).toList();
        }
      }
      // StoreKit 2
      else if (product is AppStoreProduct2Details) {
        print('StoreKit 2 产品暂不支持折扣信息获取');
      }

      return null;
    } catch (e) {
      print('获取折扣信息失败: $e');
      return null;
    }
  }

  /// 购买产品
  Future<void> purchaseProduct(ProductDetails? product) async {
    try {
      if (product == null) {
        print('未找到对应的产品');
        return;
      }
      if (isPurchasing.value) {
        print('正在购买');
        return;
      }

      isPurchasing.value = true;
      HttpRequest.instance.requestNetwork<PayOrderSuccess>(
        Api.payOrder,
        method: "GET",
        queryParameters: {
          'refer': Global.platformRefer,
          'store_product_id': product.id,
        },
        onSuccess: (data) async {
          currentPayOrder = data?.order_no;
          try {
            final bool success = await InAppPurchase.instance.buyNonConsumable(
              purchaseParam: PurchaseParam(productDetails: product),
            );
            if (success) {
            } else {
              Get.snackbar(
                'Failed',
                'purchase failed',
                snackPosition: SnackPosition.BOTTOM,
              );
              isPurchasing.value = false;
            }
          } catch (e) {
            print('购买失败: $e');
            isPurchasing.value = false;
            // Get.snackbar('失败', '购买请求失败', snackPosition: SnackPosition.BOTTOM);
          }
        },
        onError: (code, message) {
          print('购买失败: $code, $message');
          isPurchasing.value = false;
          Get.snackbar(
            'Failed',
            'purchase failed',
            snackPosition: SnackPosition.BOTTOM,
          );
        },
      );
    } catch (e) {
      Get.snackbar(
        'Error',
        'purchase exception: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('购买异常: $e');
      isPurchasing.value = false;
    }
  }

  /// 恢复购买
  Future<void> restorePurchases() async {
    print('restore purchases...');
    try {
      await InAppPurchase.instance.restorePurchases();
      Get.snackbar(
        'Success',
        'restore purchases success',
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        'Error',
        'restore purchases failed: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('恢复购买失败: $e');
    }
  }

  /// 监听购买状态变化
  void _listenToPurchaseUpdates() {
    InAppPurchase.instance.purchaseStream.listen((
      List<PurchaseDetails> purchaseDetailsList,
    ) {
      _handlePurchaseUpdates(purchaseDetailsList);
    });
  }

  /// 处理购买状态更新
  void _handlePurchaseUpdates(List<PurchaseDetails> purchaseDetailsList) {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      print('购买状态: ${purchaseDetails.status}');
      switch (purchaseDetails.status) {
        case PurchaseStatus.pending:
          Get.snackbar('提示', '购买处理中...', snackPosition: SnackPosition.BOTTOM);
          break;
        case PurchaseStatus.purchased:
        case PurchaseStatus.restored:
          _handleSuccessfulPurchase(purchaseDetails);
          break;
        case PurchaseStatus.error:
          Get.snackbar(
            '错误',
            '购买失败: ${purchaseDetails.error?.message}',
            snackPosition: SnackPosition.BOTTOM,
          );
          break;
        case PurchaseStatus.canceled:
          Get.snackbar('提示', '购买已取消', snackPosition: SnackPosition.BOTTOM);
          break;
      }

      if (purchaseDetails.pendingCompletePurchase) {
        InAppPurchase.instance.completePurchase(purchaseDetails);
      }
    }
  }

  /// 处理成功购买
  void _handleSuccessfulPurchase(PurchaseDetails purchaseDetails) {
    // 验证购买
    _verifyPurchase(purchaseDetails);

    // Get.snackbar('成功', '购买成功！', snackPosition: SnackPosition.BOTTOM);

    // 更新用户订阅状态
    _updateSubscriptionStatus(purchaseDetails.productID);
  }

  /// 验证购买
  void _verifyPurchase(PurchaseDetails purchaseDetails) {
    if (currentPayOrder == null) {
      return;
    }
    HttpRequest.instance.requestNetwork<BaseEntity<dynamic>>(
      Api.verifyOrder,
      method: "POST",
      params: {
        'order_no': currentPayOrder,
        'product_id': purchaseDetails.productID,
        'transactionId': purchaseDetails.purchaseID,
        'receipt_data': purchaseDetails.verificationData.localVerificationData,
      },
      onSuccess: (data) {
        isPurchasing.value = false;
        Global.updateMineInfo();
        Get.snackbar('成功', '购买成功！', snackPosition: SnackPosition.BOTTOM);
      },
      onError: (error, stackTrace) {
        isPurchasing.value = false;
        Get.snackbar('失败', '验证购买失败', snackPosition: SnackPosition.BOTTOM);
      },
    );
    // print('验证购买: ${purchaseDetails.productID}');
    // print('交易ID: ${purchaseDetails.purchaseID}');
    // print('收据: ${purchaseDetails.verificationData.localVerificationData}');
  }

  /// 更新订阅状态
  void _updateSubscriptionStatus(String productId) {
    // 根据产品ID更新对应的订阅状态
    print('更新订阅状态: $productId');
    // TODO: 实现订阅状态更新逻辑
  }

  String periodText(int circle) {
    switch (circle) {
      case 1:
        return 'week';
      case 2:
        return 'month';
      case 3:
        return 'season';
      case 4:
        return 'year';
      default:
        return 'month';
    }
  }
}
